package com.rfsp.common.config;

import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 配置全局事务
 * @author: DongFangQi
 * @Date: Created in 2019/8/19 4:40 PM
 */
@Aspect
@Configuration
public class TransactionConfig {
	
    private final static Logger logger = LoggerFactory.getLogger(TransactionConfig.class);

    private String aopPointcut = "execution(* com.rfsp.*.service.*Service.*(..))";
    
    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice(){
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();

        /** 只读事务，不做更新操作 */
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        /** 当前存在事务就使用当前事务，当前不存在事务就创建一个新的事务 */
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();

        /** 什么异常需要回滚 */
        requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredTx.setTimeout(50000);

        Map<String, TransactionAttribute> methodMap = new HashMap<>();

        /** 可以提及事务或回滚事务的方法 */
        methodMap.put("add*", requiredTx);
        methodMap.put("save*", requiredTx);
        methodMap.put("update*", requiredTx);
        methodMap.put("modify*", requiredTx);
        methodMap.put("edit*", requiredTx);
        methodMap.put("insert*", requiredTx);
        methodMap.put("delete*", requiredTx);
        methodMap.put("remove*", requiredTx);
        methodMap.put("repair*", requiredTx);
        methodMap.put("binding*", requiredTx);
        methodMap.put("create*", requiredTx);
        methodMap.put("cancel*", requiredTx);
        methodMap.put("revoke*", requiredTx);
        

        /** 其他方法无事务，只读 */
        methodMap.put("*", readOnlyTx);
        source.setNameMap(methodMap);

        TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source);
        return txAdvice;
    }

    @Bean(name = "txAdviceAdvisor")
    public Advisor txAdviceAdvisor() {
        logger.info("===============================创建txAdviceAdvisor===================================");
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(aopPointcut);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }

    /**
     * 对于大批量数据处理，建议分成多个小事务，每个事务处理少量数据。
     * 这样即使某个小事务失败，也不会影响整体进度，
     * 而且可以及时释放数据库锁，提高系统并发性能。
     * @param dataList
     */
//    @Transactional(timeout = 30, rollbackFor = Exception.class)
    public void batchProcess(List dataList) {
        // 分批处理，避免长事务
        int batchSize=100;
        for (int i=0; i < dataList.size(); i += batchSize) {
            List batch = dataList.subList(i, Math.min(i + batchSize, dataList.size()));
//            数据处理逻辑代码;
        }
    }
}